/**
 * 
 */
package org.gov.vis.components;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Rectangle2D;
import java.util.LinkedList;

import javax.swing.JLabel;

/**
 * 
 *
 */
public class VISHyperLink extends JLabel {

	private final Color LINK_COLOR  = Color.BLUE;
	protected boolean underline;
	
	/*
	 * this field will be useful to set an ID to a component.
	 * which helps uniquely identifying a component
	 */
	private long id;
	
	private Object object;

	protected LinkedList<ActionListener> actionListenerList = new LinkedList<ActionListener>();



	public VISHyperLink(String text) 
	{
		super(text);
		setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		setForeground(LINK_COLOR);
		addMouseListener( mouseListener );
	} // end of one argument constructor



	protected MouseListener mouseListener = new MouseAdapter() {
		public void mouseEntered(MouseEvent me) {
			underline = true;
			repaint();
		}

		public void mouseExited(MouseEvent me) {
			underline = false;
			repaint();
		}
		public void mouseClicked(MouseEvent me) 
		{       
			fireActionEvent();
		}
	};


	// adds all listener into the list
	public void addActionListener(ActionListener al) {
		if(!actionListenerList.contains( al )) {
			actionListenerList.add( al );
		}
	}

	//called when ever mouse is pressed.
	protected void fireActionEvent() 
	{
		ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getText());
		for(ActionListener l : actionListenerList ) {
			l.actionPerformed( e );
		}
	}// end of fireActionEventMethod



	public void paint(Graphics g) 
	{
		super.paint(g);
		if (underline)
		{ 
			// really all this size stuff below only needs to be recalculated if font or text changes
			Rectangle2D textBounds =  getFontMetrics(getFont()).getStringBounds(getText(), g);

			//this layout stuff assumes the icon is to the left, or null
			int y = getHeight()/2 + (int)(textBounds.getHeight()/2);
			int w = (int) textBounds.getWidth();
			int x = getIcon()==null ? 0 : getIcon().getIconWidth() + getIconTextGap(); 

			g.setColor(getForeground());
			g.drawLine(0, y, x + w, y);
		}
	}// end of paint method.

	/**
	 * @return the id
	 */
	public long getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(long id) {
		this.id = id;
	}

	/**
	 * @return the object
	 */
	public Object getObject() {
		return object;
	}

	/**
	 * @param object the object to set
	 */
	public void setObject(Object object) {
		this.object = object;
	}

}
